﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Casamiel.Domain;
using Casamiel.Domain.Entity;
using Dapper;
using Smooth.IoC.Repository.UnitOfWork;
using Smooth.IoC.UnitOfWork.Interfaces;

namespace Casamiel.Infrastructure.Repositories
{
	public class BaseMemberConponsRepository : BaseRepository<BaseMemberCoupons, long>, IBaseMemberConponsRepository
	{
		public BaseMemberConponsRepository(IDbFactory factory) : base(factory)
		{
		}


		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="TSession"></typeparam>
		/// <param name="ProductId"></param>
		/// <param name="State"></param>
		/// <returns></returns>
		public async Task<List<BaseMemberCoupons>> GetListAsync<TSession>(int ProductId, int State,int top ) where TSession : class, ISession
		{
			using var session = Factory.Create<TSession>();
			var list = await session
.QueryAsync<BaseMemberCoupons>($"SELECT top {top} * FROM {Sql.Table<BaseMemberCoupons>(session.SqlDialect)} where  State=@State and ProductId=@ProductId", new { State, ProductId })
.ConfigureAwait(false);
			return list.ToList();
		}


		/// <summary>
		/// 
		/// </summary>
		/// <param name="TicketCode"></param>
		/// <param name="NewState"></param>
		/// <param name="OldState"></param>
		/// <param name="uow"></param>
		/// <returns></returns>
		public async Task<bool> UpdateAsync(string TicketCode, int NewState, int OldState, IUnitOfWork uow)
		{
			if (uow is null) {
				throw new ArgumentNullException(nameof(uow));
			}

			var sql = $"update  {Sql.Table<BaseMemberCoupons>(uow.SqlDialect)} set State=@NewState,UpdateTime=getdate() where TicketCode=@TicketCode and State=@OldState";

			return await uow.Connection.ExecuteAsync(sql.CheckSafeSql(), new { TicketCode, NewState, OldState }, uow.Transaction).ConfigureAwait(true) > 0;
		}
	}
}
